package com.noahplat.fourg.netty;

import com.noahplat.common.utils.GatewayService;
import com.noahplat.fourg.service.FourgService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 端口监听类，处理接收到的数据
 */
@Component
@ChannelHandler.Sharable
public class NettyHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private BeanFactory beanFactory;

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        GatewayService.removeGatewayChannel(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            IdleState state = ((IdleStateEvent) evt).state();
            if(state == IdleState.READER_IDLE){
                ctx.channel().close();
            }
        }else {
            super.userEventTriggered(ctx, evt);
        }
    }

    /**
     * 获取设备数据
     * @param ctx   上下文
     * @param msg   设备传过来的数据
     * @throws Exception
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //将接收的数据放到ByteBuf中
        ByteBuf buf =null;
        try {//发生手动释放buf，否则会造成内存泄漏
            buf = (ByteBuf) msg;
            String readMessage = buf.toString(CharsetUtil.UTF_8);
            if("[".equals(readMessage.substring(0,1))){
                //每次接收登录包时，将接收到的channel缓存
                String imei = readMessage.split("\\*")[1];
                GatewayService.addGatewayChannel(imei, ctx);
                //处理数据
                String message = readMessage.substring(1, readMessage.length() - 1);
                FourgService fourgService = beanFactory.getBean(FourgService.class);
                fourgService.getDeviceData(message, ctx, imei);
            }
        } finally {
            buf.release();
        }
    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
